package main

import "strings"

func reverseWords(s string) string {
	var words []string
	beg := -1
	if s[0] != ' ' {
		beg = 0
	}
	for i, ch := range s {
		if ch == ' ' {
			if beg < 0 { // 无意义空格
				continue
			} else { // 单词的结尾
				word := s[beg:i]
				words = append(words, word)
				beg = -1
			}
		} else {
			if beg < 0 { // 单词的开始
				beg = i
			} else { // 单词中间
				continue
			}
		}
	}
	if beg >= 0 {
		words = append(words, s[beg:])
	}
	sb := strings.Builder{}
	for i := len(words) - 1; i >= 0; i-- {
		word := words[i]
		sb.WriteString(word)
		if i > 0 {
			sb.WriteString(" ")
		}
	}
	return sb.String()
}

func main() {
	println(reverseWords(" hello"))
	println(reverseWords("hello"))
	println(reverseWords("  hello world  "))
	println(reverseWords("a good   example"))
	println(reverseWords("the sky is blue"))

}
